package com.xique.door.controller;

import cn.hutool.core.util.StrUtil;
import com.xique.door.util.WechatUtils;
import com.xique.door.wechat.service.WechatMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author HdongSun
 */
@RequestMapping("/wx/gzh")
@RestController
@RequiredArgsConstructor
@Slf4j
public class WechatGzhNotifyController extends BaseUserController {

    @Value("${wx.gzh.token}")
    private String token;

    private final WechatUtils wechatUtils;

    private final WechatMessageService wechatMessageService;

    @RequestMapping(value = "/notify", produces = "text/html;charset=UTF-8")
    public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        PrintWriter out = null;

        if (request.getMethod().matches("GET")) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");

            out = response.getWriter();

            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (wechatUtils.checkSignature(signature, token, timestamp, nonce)) {
                out.print(echostr);
            }
            out.close();
        }

        try {
            String respMessage = wechatMessageService.callback(request);
            if (StrUtil.isBlank(respMessage)) {
                log.info("不回复消息");
                return;
            }
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.print(respMessage);
        } catch (Throwable e) {
            log.error("微信发送消息失败", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
